package com.yanq.liancar.activity;
/*
 *  @创建者     liyan
 *  @创建时间   2018/11/11  17:26
 *  @描述       ${TODO}
 */


import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogSure;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.bean.QueryByoNumBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TestCodeActivity extends BaseToolbarActivity {
    @BindView(R.id.et_yzm)
    EditText etYzm;
    @BindView(R.id.img_delete)
    ImageView imgDelete;
    @BindView(R.id.text1)
    TextView text1;
    @BindView(R.id.text2)
    TextView text2;
    @BindView(R.id.text3)
    TextView text3;
    @BindView(R.id.text4)
    TextView text4;
    @BindView(R.id.text5)
    TextView text5;
    @BindView(R.id.text6)
    TextView text6;
    @BindView(R.id.text7)
    TextView text7;
    @BindView(R.id.text8)
    TextView text8;
    @BindView(R.id.text9)
    TextView text9;
    @BindView(R.id.text0)
    TextView text0;
    @BindView(R.id.text_sure)
    TextView textSure;
    private RxDialogSure mRxDialog;
    private boolean textCursor = false;
    private int sid;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this).statusBarColor(R.color.white).statusBarDarkFont(true).init();
        setContentView(R.layout.activity_testcode);
        ButterKnife.bind(this);
        hideSoftInputMethod();
        mTvTitle.setText("订单号验券");

        sid=getIntent().getIntExtra("sid",0);
        //显示软键盘
        //showSoftInputFromWindow(this, etYzm);
        etYzm.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    //隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(TestCodeActivity.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //自己需要的操作
                    if (!TextUtils.isEmpty(etYzm.getText().toString().trim())) {
                        initOkGo(etYzm.getText().toString().trim());
                    }
                    return true;
                }
                return false;
            }
        });

        etYzm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //设置光标为可见状态
                etYzm.setCursorVisible(true);
                textCursor = true;
            }
        });

        imgDelete.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                etYzm.setText("");
                return true;
            }
        });

        imgDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteContent();
            }
        });

    }


    /**
     * EditText获取焦点并显示软键盘
     */
    public static void showSoftInputFromWindow(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    //验证：验证码
    private void initOkGo(String str) {
        OkGo.<String>post(Config.s + "llc/carServiceOrderController/queryByoNum")
                .tag(this)
                .params("oNum", str)
                .params("shopid", sid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        QueryByoNumBean byoNumBean = gson.fromJson(response.body(), QueryByoNumBean.class);
                        if (byoNumBean.isIsSuccess()) {
                            if (byoNumBean.getCode() == 200) {
                                etYzm.setText("");
                                if (byoNumBean.getData().getOrder().getServiceType()==5){
                                    Bundle bundle=new Bundle();
                                    bundle.putString("oNum",byoNumBean.getData().getOrder().getOnum());
                                    RxActivityTool.skipActivity(TestCodeActivity.this, SheetMetalActivity.class,bundle);
                                }else {
                                    Intent intent = new Intent(TestCodeActivity.this, VerificationResultActivity.class);
                                    intent.putExtra("code", byoNumBean.getData().getOrder().getOnum());
                                    intent.putExtra("shopName", byoNumBean.getData().getShop().getShopName());
                                    intent.putExtra("serviceName", byoNumBean.getData().getOrder().getServiceName());
                                    startActivity(intent);
                                }
                            } else {
                                dialog(byoNumBean.getOutputMessage());
                            }
                        } else {
                            RxToast.error(byoNumBean.getOutputMessage());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        RxToast.error("服务器连接错误");
                    }
                });
    }

    private void dialog(String str) {
        mRxDialog = new RxDialogSure(this);
        mRxDialog.setTitle("验证码错误");
        mRxDialog.setContent(str);

        mRxDialog.setSureListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRxDialog.dismiss();
                etYzm.setText("");
            }
        });
    }

    public void hideSoftInputMethod() {
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        int currentVersion = Build.VERSION.SDK_INT;
        String methodName = null;
        if (currentVersion >= 16) {
            // 4.2
            methodName = "setShowSoftInputOnFocus";
        } else if (currentVersion >= 14) {
            // 4.0
            methodName = "setSoftInputShownOnFocus";
        }
        if (methodName == null) {
            etYzm.setInputType(InputType.TYPE_NULL);
        } else {
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus;
            try {
                setShowSoftInputOnFocus = cls.getMethod(methodName,
                        boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(etYzm, false);
            } catch (NoSuchMethodException e) {
                etYzm.setInputType(InputType.TYPE_NULL);
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    @OnClick({R.id.text1, R.id.text2, R.id.text3, R.id.text4, R.id.text5, R.id.text6, R.id.text7, R.id.text8, R.id.text9, R.id.text0, R.id.text_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text1:
                setContet("1");
                break;
            case R.id.text2:
                setContet("2");
                break;
            case R.id.text3:
                setContet("3");
                break;
            case R.id.text4:
                setContet("4");
                break;
            case R.id.text5:
                setContet("5");
                break;
            case R.id.text6:
                setContet("6");
                break;
            case R.id.text7:
                setContet("7");
                break;
            case R.id.text8:
                setContet("8");
                break;
            case R.id.text9:
                setContet("9");
                break;
            case R.id.text0:
                setContet("0");
                break;
            case R.id.text_sure:
                if (!TextUtils.isEmpty(etYzm.getText().toString().trim())) {
                    initOkGo(etYzm.getText().toString().trim());
                } else {
                    RxToast.error("请输入订单号码");
                }
                break;
        }
    }

    //输入
    private void setContet(String str) {
//        etYzm.setText((etYzm.getText().toString() + str));
//        etYzm.setSelection((etYzm.getText().toString() + str).length() - 1);

        StringBuilder sb = new StringBuilder(etYzm.getText().toString().trim());
        int index=0;
        if (textCursor==true){
            index=etYzm.getSelectionStart();
            sb=sb.insert(index,str);
            etYzm.setText(sb.toString());
            etYzm.setSelection(index+1);
        }else {
            sb=sb.append(str);
            etYzm.setText(sb.toString());
            etYzm.setSelection((etYzm.getText().toString() + str).length() - 1);
        }

    }

    //删除
    private void deleteContent() {
        getCursorCoordinate();

    }

    private void getCursorCoordinate() {
        StringBuffer sb = new StringBuffer(etYzm.getText().toString().trim());
        int index = 0;
        if (textCursor == true) {
            index = etYzm.getSelectionStart();
            if (index > 0) {
                sb = sb.delete(index - 1, index);
            }
        } else {
            index = etYzm.length();
            if (index > 0) {
                sb = sb.delete(index - 1, index);
            }
        }
        etYzm.setText(sb.toString());
        if (index > 0) {
            Selection.setSelection(etYzm.getText(), index - 1);
        }
        if (etYzm.getText().toString().trim().length() <= 0) {
//          etYzm.setCursorVisible(false);
            textCursor = false;
        }

    }

}
